<script setup lang='ts'>
import type { DeptDetailResult } from "@/api/types";
import { ElMessage, ElMessageBox } from "element-plus";
import { computed } from "vue";
import { deptApi } from "@/api";
import DeptTree from "@/components/ReCommon/src/tree/deptTree";
import { $t } from "@/plugins/i18n";
import { useLayoutStore } from "@/stores/layout";
import { apiCall } from "@/utils/http/apiCall";
import { fmtTableData } from "@/utils/tools";
import FormDialog from "./components/FormDialog.vue";
import { useDeptFormDialog, useDeptTable, useDeptTree } from "./composables";

defineOptions({
    name: "SysDepart",
});

const device = computed(() => useLayoutStore().device);

const {
    deptTreeRef,
    deptData,
    nodeClick,
    removeNodeFromTree,
} = useDeptTree();

const {
    tableLoading,
    tableData,
    fetchTableData,
} = useDeptTable();

const {
    dialogVisible,
    dialogMode,
    openAddDialog,
    openEditDialog,
} = useDeptFormDialog();

/** 对话框 - 编辑成功 */
function onUpdateSuccess(data: DeptDetailResult): void {
    // 更新当前选中部门信息
    if (deptData.value?.id === data.id) {
        Object.assign(deptData.value, data);
    }
}

/** 删除部门 */
async function handleDelete(): Promise<void> {
    if (!deptData.value) {
        ElMessage.warning($t("placeholder.selectDeleteDepartment"));
        return;
    }

    await ElMessageBox.confirm(
        `${$t("description.deleteConfirmDefinitely")} "${deptData.value.name}" ?`,
        $t("button.delete"),
        {
            confirmButtonText: $t("button.confirm"),
            cancelButtonText: $t("button.cancel"),
            type: "warning",
        },
    );

    apiCall(
        () => deptApi.remove(deptData.value!.id),
        (code) => {
            ElMessage.success($t("resp.handleSuccess"));
            const treeRef = deptTreeRef.value?.innerTreeRef;
            const parentCode = treeRef?.getCurrentNode()?.code?.split(".").slice(0, -1).join(".");
            const parent = treeRef?.getNode(parentCode)?.data as DeptDetailResult || null;
            removeNodeFromTree(code);
            deptData.value = parent || null; // 重置为父节点或空
            if (parent) fetchTableData(parent.id);
        },
    );
}
</script>

<template>
    <el-card>
        <div class="dept-page" :class="{ 'gap-0!': device === 'mobile' }">
            <div class="left overflow-hidden" :class="{ hidden: device === 'mobile' }">
                <DeptTree
                    ref="deptTreeRef"
                    :lazy="true"
                    @node-click="(data) => nodeClick(data, () => fetchTableData(data.id))"
                />
            </div>
            <div class="right">
                <el-descriptions
                    class="mb-4"
                    :title="deptData?.name || $t('label.deptInfo')"
                    :column="2"
                >
                    <template #extra>
                        <el-button type="primary" @click="openAddDialog(!!deptData)">
                            {{ $t("button.add") }}
                        </el-button>
                        <el-button type="warning" @click="openEditDialog(deptData?.id)">
                            {{ $t("button.edit") }}
                        </el-button>
                        <el-button type="danger" @click="handleDelete">
                            {{ $t("button.delete") }}
                        </el-button>
                    </template>
                    <el-descriptions-item :label="$t('label.depart')">
                        {{ deptData?.fullName || '/' }}
                    </el-descriptions-item>
                    <el-descriptions-item :label="$t('label.deptType')">
                        {{ deptData?.typeName || '/' }}
                    </el-descriptions-item>
                    <el-descriptions-item :label="$t('label.phone')">
                        {{ deptData?.phone || '/' }}
                    </el-descriptions-item>
                    <el-descriptions-item :label="$t('label.email')">
                        {{ deptData?.email || '/' }}
                    </el-descriptions-item>
                    <el-descriptions-item :label="$t('label.remark')" :span="2">
                        {{ deptData?.remark || '/' }}
                    </el-descriptions-item>
                </el-descriptions>
                <el-page-table
                    :loading="tableLoading"
                    :data="tableData"
                    :page="false"
                    :fetch-data="() => fetchTableData(deptData?.id)"
                >
                    <el-table-column prop="name" :label="$t('label.childDeptName')" />
                    <el-table-column prop="typeName" :label="$t('label.deptType')" show-overflow-tooltip :formatter="({ typeName }) => fmtTableData().text(typeName)" />
                </el-page-table>
            </div>
        </div>

        <!-- 新增/编辑部门对话框 -->
        <FormDialog
            v-model:visible="dialogVisible"
            :mode="dialogMode"
            :parent-dept="deptData"
            :tree-ref="deptTreeRef"
            @create-success="fetchTableData(deptData?.id)"
            @update-success="onUpdateSuccess"
        />
    </el-card>
</template>

<style scoped>
.dept-page {
    display: flex;
    gap: 16px;
}

.left {
    width: 280px;
    padding-right: 16px;
    border-right: 1px solid var(--el-border-color-light);
}

.right {
    flex: 1;
    min-width: 0;
}
</style>
